package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.constants.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	//注入JmsTemplate
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	

	@Action(value="customer_sendSms")
	public String sendSms(){
		//产生4位随机验证码
		String checkCode = RandomStringUtils.randomNumeric(4);
		//把验证码存入session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),checkCode);
		
		System.out.println("验证码发送成功:"+checkCode);
		//向目标用户发送的信息
		final String msg = "尊敬的用户，验证码为："+checkCode+"服务热线为110";
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		
		
		return NONE;
		
	}
	
	//属性驱动 接收页面传回的验证码
	private String checkCode;
	
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}
	//注入spring data Redis
	private RedisTemplate<String,String> redisTemplate;
	
	public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	//提交注册表单，校验session中的checkcode和页面中传入的是否一致
	@Action(value="customer_regist", results={@Result(name="success",location="signup-success.html",type="redirect"),
			                         @Result(name="input",location="signup.html",type="redirect")} )
	public String regist(){
	
		//取出session中的验证码
		String checkCodeSesion = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		System.out.println("session中的验证码"+checkCodeSesion);
		System.out.println("页面传回的验证码"+checkCode);
		if(StringUtils.equals(checkCodeSesion,checkCode)){
			//相等   crm_customer中添加客户
			System.out.println("短信验证成功...............");
			WebClient
			.create("http://localhost:9002/crm_management/services/customerService/customer")
			.accept(MediaType.APPLICATION_JSON).post(model);
			
			//向客户邮箱发送激活邮件
			String activeCode = RandomStringUtils.randomNumeric(32);
			
			//把激活码存入redis缓存器中，并设置保留24个小时
			redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 3, TimeUnit.MINUTES);
			
			//发送邮件
			String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
					+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
					+ "&activeCode=" + activeCode + "'>速运快递邮箱绑定地址</a>";
			MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
			System.out.println(content);
			
			
			
			return SUCCESS;
		}else{
			//不等
			System.out.println("短信验证码错误.....");
			return INPUT;
		}
		
	}
	
	//属性驱动  接收从邮箱转发回的激活码
	private String activeCode;
	
	
	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	@Action("customer_activeMail")
	public String activeMail(){
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		String activeCodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		//判断从网页传回的激活码和redis中是否相等
		
		if(StringUtils.equals(activeCodeRedis, activeCode)){
			//激活码有效

			//调用customerService的方法根据电话号码查询客户，状态码是否已经update
			Customer customer = WebClient
			.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"+model.getTelephone())
			.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println("customer................"+customer.toString()+"................"+customer.getType());
			
			//判断状态码是否为1
			if (customer.getType() == null || customer.getType() != 1) {
				//邮箱没有激活
				try {
					WebClient
					.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"+model.getTelephone())
					.get();
					ServletActionContext.getResponse().getWriter().print("邮箱已绑定成功");
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			
				
			}else{
				//邮箱已经激活，提示不能重复激活
				
				try {
					ServletActionContext.getResponse().getWriter().print("邮箱已绑定，请勿重复绑定");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
			//激活码无效
			try {
				ServletActionContext.getResponse().getWriter().print("激活码无效，请登录网页，重新绑定邮箱");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//删除redis
		redisTemplate.delete(model.getTelephone());
		return NONE;
	}
	
	//用户登录功能
	@Action(value="customer_login", results={@Result(name="login", location="login.html",type="redirect"),
			@Result(name="success", location="index.html#/myhome", type="redirect")})
	public String login(){
		//System.out.println(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/login?telephone="+model.getTelephone()+"&password="+model.getPassword()+"--------------------------------------");
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/login?telephone="+model.getTelephone()+"&password="+model.getPassword())
		.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		
		if(customer==null){
			//登陆失败
			
			return "login";
		}
		
		//登陆成功
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		return SUCCESS;
	}
	
}
